﻿using System;
using System.Windows.Forms;

namespace Z.IconLibraryGenerator.WinForm
{
    public partial class MainForm : Form
    {
        /// <summary>The hook timer.</summary>
        private readonly Timer HookTimer = new Timer {Interval = 50, Enabled = true};

        /// <summary>Default constructor.</summary>
        public MainForm()
        {
            InitializeComponent();

            Text = @"Icon Library Generator";
            this.ToFullScreen();
            uiWebBrowser.Url = new Uri(My.Url.Default);

            HookTimer.Tick += HookTimer_Tick;
        }

        /// <summary>Event handler. Called by HookTimer for tick events.</summary>
        /// <param name="sender">Source of the event.</param>
        /// <param name="e">Event information.</param>
        private void HookTimer_Tick(object sender, EventArgs e)
        {
            if (uiWebBrowser.ReadyState == WebBrowserReadyState.Complete && !IsActionHooked())
            {
                My.PageType page = GetPage();

                if (page == My.PageType.Default)
                {
                    My.CurrentPage = new Default(uiWebBrowser);
                }
                else if (page == My.PageType.ProjectExecute)
                {
                    My.CurrentPage = new ProjectExecute(uiWebBrowser);
                }
                else if (page == My.PageType.ProjectSettings)
                {
                    My.CurrentPage = new ProjectSettings(uiWebBrowser);
                }

                SetActionHook();
            }
        }

        /// <summary>Query if this object is action hooked.</summary>
        /// <returns>true if action hooked, false if not.</returns>
        public bool IsActionHooked()
        {
            return My.BodyHook == uiWebBrowser.Document.Body;
        }

        /// <summary>Sets action hook.</summary>
        public void SetActionHook()
        {
            My.BodyHook = uiWebBrowser.Document.Body;
        }

        /// <summary>Gets the page.</summary>
        /// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
        /// <returns>The page.</returns>
        public My.PageType GetPage()
        {
            if (uiWebBrowser.Url.AbsoluteUri == new Uri(My.Url.Default).AbsoluteUri)
            {
                return My.PageType.Default;
            }
            if (uiWebBrowser.Url.AbsoluteUri == new Uri(My.Url.ProjectExecute).AbsoluteUri)
            {
                return My.PageType.ProjectExecute;
            }
            if (uiWebBrowser.Url.AbsoluteUri == new Uri(My.Url.ProjectSettings).AbsoluteUri)
            {
                return My.PageType.ProjectSettings;
            }

            throw new Exception("Invalid Page");
        }
    }
}